<template>
  <div v-if="cartList.length > 0">
    <el-row class="title">
      <el-col :span="2">
        <el-checkbox label="全选"
                     v-model="checkAllState"
                     @change="cheackAllOrNon"
                     :indeterminate="halfState"
        />
      </el-col>
      <el-col :span="11">商品</el-col>
      <el-col :span="2">单价</el-col>
      <el-col :span="6">数量</el-col>
      <el-col :span="2">小计</el-col>
      <el-col :span="1">操作</el-col>
    </el-row>
    <el-row v-for=" (cart, index) in cartList" :key="index" class="cartItem">
      <el-col :span="2">
        <el-checkbox
            v-model="cart.checkState"
            @change="changState"
        />
      </el-col>
      <el-col :span="2">
        <el-image
            :src="`${SERVER_ADDR}/goods/pic/${cart.goods.picList[0].url}`"
            style="height: 50px; width: 50px;"
            fit="contain"
        />
      </el-col>
      <el-col :span="5">{{ cart.goods.name }}</el-col>
      <el-col :span="4">{{ `${cart.goods.color}-${cart.goods.version}` }}</el-col>
      <el-col :span="2">{{ cart.goods.price.toFixed(2) }}</el-col>
      <el-col :span="6">
        <el-input-number
            v-model="cart.count"
            :min="1"
            size="small"
            @change="updateCount(cart)"
        />
      </el-col>
      <el-col :span="2">{{ (cart.goods.price * cart.count).toFixed(2)}}</el-col>
      <el-col :span="1">
        <el-button type="danger" :icon="Delete" circle @click="deleteById(cart.id)" />
      </el-col>
    </el-row>
    <el-row class="cartFooter">
      <el-col :span="2">
        <el-checkbox label="全选"
                     v-model="checkAllState"
                     @change="cheackAllOrNon"
                     :indeterminate="halfState"
        />
      </el-col>
      <el-col :span="3">
        <el-link :underline="false" @click="deleteChecked">删除选中的商品</el-link>
      </el-col>
      <el-col :span="11">
        <el-link :underline="false" @click="deleteAll">清理购物车</el-link>
      </el-col>
      <el-col :span="3">已选择{{checkCount}}件商品</el-col>
      <el-col :span="3">总价：￥{{total.toFixed(2)}}</el-col>
      <el-col :span="2">
        <el-button type="danger" @click="toCreateOrderPage">结算</el-button>
      </el-col>
    </el-row>
  </div>
  <div class="none" v-else>
    购物车空空如也，去看看心仪的商品吧<RouterLink to="/user/index">去购物</RouterLink>
  </div>
</template>

<script setup>
//当前用户的所有购物车信息
import {ref} from "vue";
import cartApi from "@/api/cartApi.js";
import {Delete} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const  router = useRouter();
//服务器的地址
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR)
const cartList = ref([]);
//全选按钮是否选中
const checkAllState = ref(false);
//没有全选的状态
const halfState = ref(false);
//选中商品的数量
const checkCount = ref(0);
//选中商品的金额
const total = ref(0);

//跳转到生成订单的页面
const toCreateOrderPage = () => {
  //获取已选中的购物车的id
  let cartIds = []
  cartList.value.forEach(cart => {
    if (cart.checkState){
      cartIds.push(cart.id)
    }
  })

  if (cartIds.length == 0) {
    ElMessage.warning("您还没有选择商品，无法进行结算");
    return
  }
  router.push({
    path: "/user/createOrder",
    query: {
      cartIds
    }
  })
};
//删除已选中的购物车
const deleteChecked = () => {
  //获取被选中的购物车的id
  let ids = [];
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      ids.push(cart.id);
    }
  });
  if (ids.length == 0) {
    ElMessage.warning("购物车中没有商品，无法删除购物车！")
    return;
  }
  cartApi.deleteByIds(ids)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg)
          //重新获取购物车的列表
          cartList.value = cartList.value.filter(cart => !cart.checkState)
          changState();
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
//清空购物车
const deleteAll = () => {
  //获取所有购物车的id
  let ids = [];
  cartList.value.forEach(cart => {
    ids.push(cart.id);
  });
  if (ids.length == 0) {
    ElMessage.warning("购物车中没有商品，无法删除购物车！")
    return;
  }
  cartApi.deleteByIds(ids)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg)
          //重新获取购物车的列表
          selectCartList();
        }else {
          ElMessage.error(resp.msg)
        }
      })
}
//
//全选-全不选
const cheackAllOrNon = ()=> {
  //让每个购物车项前面的多选按钮和全选按钮的状态保持一致
  halfState.value = false;
  cartList.value.forEach(cart => {
    cart.checkState = checkAllState.value
  })
  getCountAndTotal();
}

//购物车项前面的多选按钮状态发生变化时调用函数
const changState = ()=> {

  //如果所有的checkbox都被选中
  //如果所有的checkbox都没有被选中
  //计算选中的商品的数量，计算选中商品的金额
  let count = 0;
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      count++;
    }
  })
  if (count == cartList.value.length) {
    checkAllState.value = true;
    halfState.value = false;
  }else if (count == 0){
    checkAllState.value = false;
    halfState.value = false;
  }else {
    halfState.value = true;
  }
  getCountAndTotal();
}

//计算选中商品的数量和金额
const getCountAndTotal = ()=> {
  checkCount.value = 0;
  total.value = 0;
  cartList.value.forEach(cart => {
    if (cart.checkState) {
      checkCount.value += cart.count;
      total.value += cart.goods.price * cart.count;
    }
  })
}
//查询当前用户所有的购物车信息
const selectCartList = () => {
  cartApi.selectCartList()
      .then(resp => {
        cartList.value = resp.data;
      })
}
//根据id删除
const deleteById = (id) => {
  cartApi.delete(id)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          //删除的项从数组中清除
          cartList.value = cartList.value.filter(cart => cart.id != id)
          //设置全选按钮的状态
          changState();
        }else {
          ElMessage.error(resp.msg)
        }
        getCountAndTotal();
      })
}
//修改购物车的数量
const updateCount = (cart) => {
    cartApi.update({id: cart.id, count: cart.count})
        .then(resp => {
          if (resp.code == 10000) {
            //让购物车中的数量和数据库中保持一致
            cartApi.selectById(cart.id)
                .then(resp => {
                  cart.count = resp.data.count;
                })
            //设置全选按钮的状态
            changState();
          } else {
            ElMessage.error(resp.msg);
          }
          getCountAndTotal();
        })
}
selectCartList();
</script>

<style scoped>
  .title {
    margin: 20px 0;
    padding-left: 10px;
    font-size: 14px;
    line-height: 40px;
    height: 40px;
    background-color: #fff;
  }
  .cartItem {
    margin-bottom: 5px;
    padding-left: 10px;
    font-size: 14px;
    background-color: #ffffff;
    height: 50px;
    line-height: 50px;
  }
  .cartFooter {
    margin: 20px 0;
    padding-left: 10px;
    font-size: 14px;
    height: 40px;
    line-height: 40px;
    background-color: #fff;
  }
  .none {
    line-height: 300px;
    height: 300px;
    text-align: center;
    background-color: #ffffff;
  }
</style>